import { defineComponent } from 'vue';
import { BpmnStore } from '../../bpmn/store';
import './downloader.css'

export default defineComponent({
  name: "Downloader",
  setup() {
    const bpmnContext = BpmnStore;

    // 下载文件
    const downloadFile = (name: string, data: string) => {
      var encodedData = encodeURIComponent(data);
      if (data) {
        const link = document.createElement("a");
        link.href = "data:application/bpmn20-xml;charset=UTF-8," + encodedData;
        link.setAttribute("download", name);
        link.click();
      }
    };

    // 下载BPMN文件
    const downloadBPMN = async () => {
      const { xml } = await bpmnContext.getXML();
      downloadFile("diagram.bpmn", xml);
    };

    // 下载svg文件
    const downloadSVG = async () => {
      const { svg } = await bpmnContext.getSVG();
      downloadFile("diagram.svg", svg);
    };

    return () => (
      <ul class="buttons">
        <li>
          下载
        </li>
        <li>
          <el-button onClick={() => downloadBPMN()}>
            BPMN diagram
          </el-button>
        </li>
        <li>
          <el-button onClick={() => downloadSVG()}>
            SVG image
          </el-button>
        </li>
      </ul>
    )
  }
})